/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import dao.BookDao;
import dao.MemberDao;
import dao.OrderDao;
import entity.Book;
import entity.Member;
import entity.OrderForm;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import service.Money;

/**
 *
 * @author zhang
 */
@WebServlet("/bs")
public class BuyServlet extends HttpServlet{

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name=(String)req.getSession().getAttribute("username");
        Member member=new MemberDao().getMemberByName(name);
        
        
        
        int bookId=Integer.parseInt(req.getParameter("bookid"));
        
        Book book=new BookDao().getBookById(bookId);
        int count=Integer.parseInt(req.getParameter("count1"));
        float price=book.getPrice()*count;
        
        resp.setContentType("text/html;charset=utf-8");
        if(member.getMoney()<price){
            resp.getWriter().println("<h1>支付失败，余额不足！</h1>");
        }
        else{
            new OrderDao().addOrderForm(member.getId(),Integer.parseInt(req.getParameter("address")));
            List<OrderForm> list=new OrderDao().getAllOrderForm(member.getId());
            new OrderDao().addOrderInfo(list.get(list.size()-1).getId(), book.getId(), count);
            
            //扣除金额
            new Money().deductMoney(member.getId(),price,member.getMoney());
            resp.getWriter().println("<h1>支付成功！</h1>");
        }
         resp.getWriter().println("<a href='gbbi?id="+bookId+"'>返回</a>");
    }

    
    
}
